//
//  Dictionary+URL.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/22.
//

import Foundation

extension Dictionary where Key == String, Value == Any {
    /// 将字典转换为URL查询参数字符串
    var urlQueryString: String {
        // 如果字典为空，直接返回空字符串
        guard !self.isEmpty else { return "" }
        
        let queryItems = self.compactMap { key, value -> String? in
            // 跳过空值
            if let stringValue = value as? String, stringValue.isEmpty {
                return nil
            }
            
            guard let encodedKey = key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
                  let stringValue = String(describing: value)
                    .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
                  !stringValue.isEmpty else {
                return nil
            }
            return "\(encodedKey)=\(stringValue)"
        }
        
        return queryItems.sorted().joined(separator: "&")
    }
    
    
    func base64EncodedString() -> String? {
        do {
            // 1. 将字典转换为JSON数据
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: [])
            
            // 2. 将JSON数据转换为Base64字符串
            let base64String = jsonData.base64EncodedString()
            
            return base64String
        } catch {
            print("字典转Base64失败: \(error.localizedDescription)")
            return nil
        }
    }
}
